<template>
  <Card :bordered="false" dis-hover>
    <Modal
      v-model="modalStatus"
      :loading="modalLoading"
      :title="modalTitle"
      width="800"
      @on-ok="saveUser"
    >
      <Form ref="form" :rules="rules" :model="record" show-message :label-width="140">
        <FormItem label="用户名称：" prop="userName">
          <Input v-model="record.userName" />
        </FormItem>
        <FormItem label="用户密码：" prop="userPassword">
          <Input v-model="record.userPassword" />
        </FormItem>
        <FormItem label="用户角色：" prop="userRole">
          <Select v-model="record.userRole">
            <Option v-for="item in roleLists" :value="item.id" :key="`roles_${item.id}`">{{item.roleName}}</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>
    <Form ref="formFilter" :model="queryParams" class="edit-model-form" :label-width="100">
      <Row>
        <div class="ivu-col ivu-col-span-6">
          <FormItem label="用户名称：">
            <Input placeholder="请输入用户名称" v-model="queryParams.userName" clearable />
          </FormItem>
        </div>
        <div class="ivu-col ivu-col-span-10">
          <FormItem :label-width="20">
            <Button type="primary" icon="md-search" @click="handleQuery">查询</Button>&nbsp;
            <Button type="primary" icon="md-refresh" @click="resetQuery()">重置</Button>&nbsp;
            <Button type="success" icon="md-add-circle" @click="view()">新增</Button>
          </FormItem>
        </div>
        <table-extend :columns="columns" :queryParams="queryParams" @changeTableColumns="columns = $event" @changeTableSize="tableSize = $event"></table-extend>
      </Row>
    </Form>

    <div class="content">
      <Table :loading="loading" :columns="columns" :data="data" :size="tableSize">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" style="margin-right: 8px" @click="view(index, row)">编辑</Button>
          <Button type="error" @click="doDelete(index, row)">删除</Button>
        </template>
        <Page
          slot="footer"
          :current="queryParams.pageNo"
          :total="total"
          :page-size="queryParams.pageSize"
          show-total
          @on-change="changePage"
          @on-page-size-change="changepageSize"
          :page-size-opts="[10, 20, 30]"
          show-elevator
          show-sizer
        ></Page>
      </Table>
    </div>
  </Card>
</template>

<script>
import TableExtend from "@/components/table-extend";
import { getUserList, getRoleList, addUser, editUser, delUser } from "@/api/user";
export default {
  name: "user",
  data() {
    return {
      rules: { 
        userName: {required: true, message: '用户名称不能为空', trigger: 'blur'},
        userPassword: {required: true, message: '用户密码不能为空', trigger: 'blur'},
        userRole: {required: true, message: '请选择用户角色'}
      },
      loading: false,
      modalStatus: false,
      modalLoading: true,
      modalTitle: '',
      record: {},
      total: 0,
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      columns: [
        {
          title: "",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("span", params.index + (this.queryParams.pageNo - 1) * this.queryParams.pageSize + 1);
          }
        },
        {
          title: "用户名称",
          key: "userName"
        },
        {
          title: "角色",
          key: "userRoleName"
        },
        {
          title: "操作",
          slot: "action"
        }
      ],
      data: [],
      tableSize: 'default',
      roleLists: null
    };
  },
  created() {
    this.getList();
  },
  components: {
    TableExtend
  },
  methods: {
    async getList() {
      this.loading = true;
      const [userList, roleList] = await Promise.all([
        getUserList(this.queryParams),
        this.roleLists || getRoleList()
      ])
      !this.roleLists && (this.roleLists = roleList.data);
      this.loading = false;
      this.total = userList.data.total;
      this.data = userList.data.reslute.reduce((arr,item) => {
        item.userRoleName = (this.roleLists || roleList).filter(i=>i.id==item.userRole)[0].roleName
        arr.push(item)
        return arr
      }, [])  
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    resetQuery(e) {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      };
      this.handleQuery();
    },
    // 调整页码
    changePage(page) {
      this.queryParams.pageNo = page;
      this.getList();
    },
    // 修改每页展示数量
    changepageSize(size) {
        this.queryParams.pageSize = size;
        this.getList();
    },
    // 编辑弹窗
    view(index, row) {
      this.$refs.form.resetFields();
      row ? (this.modalTitle = "编辑用户") : (this.modalTitle = "新增用户");
      this.modalStatus = true;
      this.record = { ...row };
    },
    // 删除
    doDelete(index, row) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定要删除吗？",
        onOk: () => {
          delUser({ id: row.id }).then((res) => {
            this.getList();
            this.$Message.success("删除成功");
          })
        }
      });
    },
    // 保存用户信息
    saveUser() {
      this.$refs.form.validate((valid) => {
        if(valid) {
          this.modalLoading = true
          let addOrUpDate = this.record.id ? editUser : addUser;
          addOrUpDate(this.record).then(res => {
            this.getList();
            this.$Message.success(this.record.id?"编辑成功":"新增成功");
          }).finally(()=>this.modalStatus = false);
        } else {
          this.$Message.warning("校验未通过");
          this.modalLoading = false;
          this.$nextTick(() => {
            this.modalLoading = true;
          });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.opeDrop {
  text-align: center;
}
</style>